package com.su.sweet.aop;

import com.su.sweet.annotation.Log;
import com.su.sweet.model.SysLog;
import com.su.sweet.service.SysLogService;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Action;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;

import java.util.Date;

//定义路由拦截器（放到外层一点）//环绕处理，越小越外层
@Component
public class LogAspect implements RouterInterceptor {

    @Inject
    private SysLogService sysLogService;

    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        Log anno = null;
        Action action = ctx.action();
        if (action != null) {
            anno = action.method().getAnnotation(Log.class);
        }

        if (anno == null) {
            //如果没有注解
            chain.doIntercept(ctx, mainHandler);
        } else {
            SysLog sysLog = new SysLog();
            //1.开始计时
            long start = System.currentTimeMillis();
            try {
                //2.执行主逻辑
                sysLog.setOperation(anno.operation());
                sysLog.setMethod(action.method().getName());
                sysLog.setParams(ctx.paramMap().toString());
                sysLog.setIp(ctx.realIp());
            } finally {
                //2.获得接口响应时长
                long timespan = System.currentTimeMillis() - start;
                //3.记日志
                System.out.println("用时：" + timespan);
                sysLog.setCreateTime(new Date());
                sysLog.setTime(timespan);
                sysLogService.save(sysLog);
                chain.doIntercept(ctx, mainHandler);
            }
        }
    }
}